package com.jnr.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import se.codevision.jinterlink.JInterLink;

import com.ajr.core.Settings;
import com.ajr.core.oscommerce.OSCommerceAction;
import com.ajr.core.visma.ExportResult;
import com.ajr.core.visma.OrderExport;
import com.ajr.util.MessageBundle;
import com.ajr.util.ParamUtil;

/**
 * Servlet implementation class SubmitOrder
 */
public class SubmitOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(SubmitOrder.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SubmitOrder() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String system = Settings.getInstance().getSystemPath();
		String company =  Settings.getInstance().getCompanyPath();
		String s =  Settings.getInstance().getLibraryPath();
		String page = "1";
		String orderId = "0";
		String customerId = "0";
		if(request.getParameter("page") != null && request.getParameter("page").length() > 0) {
			page = request.getParameter("page");
		}
		String redirecturl = request.getParameter("redirecturl");

		PrintWriter printWriter = response.getWriter();
		String message = "";

		ExportResult exportResult = new ExportResult();
		try {

			// Article article = JInterLinkRegisterFactory.createArticle();
			
			logger.info("queryString "+request.getQueryString());

			orderId = request.getParameter("order_id");
//			String customerAdd = request.getParameter("customerAdd");
			String orderAdd = request.getParameter("orderAdd");
			String customerUpdate = request.getParameter("customerUpdate");
			if(!Settings.getInstance().isReadConfigureOnce()) {
				Settings.getInstance().loadDataBaseConfigurations();
			}
			
			boolean insertOrder = true;
			boolean updateCustomer = true;
//			boolean insertCustomer = false;
			if(orderAdd != null && orderAdd.equalsIgnoreCase("false")) {
				insertOrder = false;
			}
			logger.info("Adding or Inserting order from url "+insertOrder);
			
			if(customerUpdate != null && customerUpdate.equalsIgnoreCase("false")) {
				updateCustomer = false;
			}
			logger.info("Updating customer flag through url "+customerUpdate);
			/*if(customerAdd != null && customerAdd.equalsIgnoreCase("true")) {
				insertCustomer = true;
			}*/
			
			if(!Settings.getInstance().isExportSpcsJInterTables() 
					|| !OSCommerceAction.isOrderExported(orderId) || !insertOrder) {
				JInterLink j = JInterLink.getInstance();
				j.open(s, system, company);
				if (orderId != null && orderId.length() > 0) {
					OrderExport orderExport = new OrderExport();
					exportResult = orderExport.exportOrder(orderId, insertOrder,updateCustomer);
					
					message= exportResult.getResultMessage();
					
					logger.info("Export order status message ["+orderId+"] "+message);
					
					if(Settings.getInstance().isExportSpcsJInterTables()) {
						if(exportResult.isStatus() && !OSCommerceAction.isOrderExported(orderId) && insertOrder) {
							exportResult.setStatus(false);
							exportResult.setMessage("26", MessageBundle.getMessage("mysql.write.failed"));
						}
					}

				}else {
					logger.info("OrderId is not available for export");
					exportResult.setMessage(ExportResult.OSC_ORDER_INVALID_CODE,MessageBundle.getMessage("invalid.orderid"));
				}

				j.close();
				
			}else {
				exportResult.setMessage("warning", MessageBundle.getMessage("order.exists"));
//				exportResult.setError();
				exportResult.setStatus(false);
			}



		} catch (Exception e) {
			exportResult.setMessage("warning", e.getMessage());
//			exportResult.setError();
			exportResult.setStatus(false);
			printWriter.write("Unable to export the order " + e.getMessage());
			logger.error("Error while exporting order", e);
			// TODO: handle exception
		}
		
		
		if(redirecturl != null && redirecturl.length() > 0) {
//			String url = (new URLDecoder().decode(redirecturl))+"&message="+exportResult.getMessage();
			int seperator = redirecturl.indexOf("?");
			String redirectUrlPart = redirecturl.substring(0,seperator);	
			String paramspart =  redirecturl.substring(seperator+1);
			HashMap paramsMap = ParamUtil.getParamsMap(paramspart);

//			paramsMap.put("messagecode",exportResult.getMessageCode());
			paramsMap.put("message",exportResult.getMessage());
			paramsMap.put("exportStatus",exportResult.getStatusCode());
			
			String url = redirectUrlPart+"?"+ParamUtil.getParams(paramsMap);
			logger.info("redirecting url "+url);
			response.sendRedirect(url);
			return;
		}else {
			response.setContentType("text/html");
//			response.setContentType("text/xml");
			response.setHeader("expires", "-1");
			
//			printWriter.write(exportResult.getHtmlResponse(page,orderId,customerId));
			printWriter.write(exportResult.getResponseText());
		}
	}
	

	


	private String removeURLParam(String redirecturl,String param) {
		String orgurl = redirecturl;
		try {
			if(redirecturl.contains(param)) {
				int index = redirecturl.indexOf(param);
				if(index >= 0) {
					int endIndex = orgurl.indexOf("&", index);
					redirecturl = orgurl.substring(0,index);
					if(endIndex >= 0) {
						redirecturl = redirecturl + orgurl.substring(endIndex);
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("Error while removing params", e);
		}
		
		return redirecturl;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		logger.info("Request comes for doPost");
		doGet(request, response);
	}

}
